package com.wb.spring.boot.autoconfigure.listener;

import com.wb.spring.boot.autoconfigure.constant.SystemConstant;
import com.wb.spring.boot.autoconfigure.register.IRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.concurrent.*;

public class WbRegisterListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IRegister register;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 注册服务到注册中心 过期时间为60秒
        register.doRegister();
        // 每隔30秒重新注册一次
        repeatRegister();
        // 每隔15秒拉取一次注册中中心的服务到本地
        repeatRefresh();
    }

    /**
     * 每隔过期时间的一半时间，去注册一次
     */
    public void repeatRegister() {
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
        scheduledExecutorService.scheduleWithFixedDelay(() ->{
            try {
                register.doRegister();
            } catch (Throwable t) {
                System.err.println("发生意外异常, 原因: " + t.getMessage());
            }
        }, SystemConstant.REDIS_REGISTER_TIME_OUT / 2, SystemConstant.REDIS_REGISTER_TIME_OUT / 2, TimeUnit.MILLISECONDS);
    }

    /**
     * 每隔过期时间的四分之一时间去拉取注册中心的服务保存到本地
     */
    public void repeatRefresh() {
        //
        ScheduledExecutorService rederScheduledExecutorService = new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory());
        rederScheduledExecutorService.scheduleWithFixedDelay(() ->{
            try {
                register.refreshServer();
            } catch (Throwable t) {
                System.err.println("发生意外异常, 原因: " + t.getMessage());
            }
        }, SystemConstant.REDIS_REGISTER_TIME_OUT / 4, SystemConstant.REDIS_REGISTER_TIME_OUT / 4, TimeUnit.MILLISECONDS);
    }
}
